/*
Copyright (c) 2008  Franklin Schmidt <fschmidt@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package fschmidt.util.locks;

import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public final class TimedLocker<T> implements Locker<T> {

	private static class Tracker {
		final ReentrantLock lock0 = new ReentrantLock();
		final Lock lock = new TimedLock(lock0);
		int waiters = 0;
	}

	private final Map<T,Tracker> map = new HashMap<T,Tracker>();

	private Tracker getTracker(T obj) {
		Tracker t = map.get(obj);
		if( t==null ) {
			t = new Tracker();
			map.put(obj,t);
		}
		return t;
	}

	private Tracker getTrackerForWait(T obj) {
		synchronized(map) {
			Tracker t = getTracker(obj);
			t.waiters++;
			return t;
		}
	}

	private void afterWait(Tracker t) {
		synchronized(map) {
			t.waiters--;
		}
	}

	private void maybeRemove(T obj,Tracker t) {
		if( t.waiters==0 && !t.lock0.isHeldByCurrentThread() ) {
			map.remove(obj);
		}
	}

	public void lock(T obj) {
		Tracker t = getTrackerForWait(obj);
		try {
			t.lock.lock();
		} finally {
			afterWait(t);
		}
	}

	public boolean tryLock(T obj) {
		synchronized(map) {
			return getTracker(obj).lock.tryLock();
		}
	}

	public boolean tryLock(T obj,long time,TimeUnit unit)
		throws InterruptedException
	{
		Tracker t = getTrackerForWait(obj);
		try {
			return t.lock.tryLock(time,unit);
		} finally {
			afterWait(t);
		}
	}

	public void unlock(T obj) {
		synchronized(map) {
			Tracker t = map.get(obj);
			t.lock.unlock();
			maybeRemove(obj,t);
		}
	}

	public boolean hasLock(T obj) {
		synchronized(map) {
			Tracker t = map.get(obj);
			return t!=null && t.lock0.isHeldByCurrentThread();
		}
	}

}
